<script setup lang="ts">
import { ref, watch } from 'vue'
import type { OrganizationVO } from '@/api/Organization.ts'
import { OrganizationApi } from '@/api/OrganizationApi.ts'
import { UserApi } from '@/api/UserApi.ts'
import { message } from 'ant-design-vue'
import { UserDeleteOutlined, LoadingOutlined } from '@ant-design/icons-vue'

const props = defineProps<{
  organization: OrganizationVO
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'success'): void
}>()

const userId = ref<string>('')
const loading = ref(false)
const userInfo = ref<any>(null)
const searchLoading = ref(false)
let searchTimer: number | null = null

// 监听用户ID输入，自动查询用户信息（防抖）
watch(userId, (newVal) => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  if (!newVal || !newVal.trim()) {
    userInfo.value = null
    return
  }

  searchTimer = setTimeout(async () => {
    try {
      searchLoading.value = true
      const user = await UserApi.getUser(newVal.trim())
      if (user) {
        userInfo.value = user
      } else {
        userInfo.value = null
      }
    } catch (error) {
      console.error('查询用户失败:', error)
      userInfo.value = null
    } finally {
      searchLoading.value = false
    }
  }, 500)
})

// 移除成员
const handleRemoveMember = async () => {
  if (!userId.value.trim()) {
    message.warning('请输入用户ID')
    return
  }

  if (!userInfo.value) {
    message.error('未找到该用户')
    return
  }

  try {
    loading.value = true
    const success = await OrganizationApi.leave({
      id: userInfo.value.id,
      organizationId: props.organization.id
    })
    
    if (success) {
      message.success('移除成员成功')
      emit('success')
      emit('close')
    } else {
      message.error('移除成员失败')
    }
  } catch (error) {
    console.error('移除成员失败:', error)
    message.error('移除成员失败：' + (error as any)?.message || '未知错误')
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  userId.value = ''
  userInfo.value = null
}
</script>

<template>
  <div class="remove-member-dialog">
    <a-alert
      message="从组织中移除成员"
      :description="`组织名称：${props.organization.name}`"
      type="warning"
      show-icon
      class="mb-4"
    />

    <!-- 输入用户ID -->
    <div class="mb-6">
      <label class="block text-sm font-medium text-gray-700 mb-2">
        用户ID
        <LoadingOutlined v-if="searchLoading" class="ml-2 text-blue-500" />
      </label>
      <a-input
        v-model:value="userId"
        placeholder="输入用户ID"
        allow-clear
        size="large"
      />
      <div v-if="userId && !searchLoading && !userInfo" class="mt-2 text-sm text-red-500">
        未找到该用户
      </div>
    </div>

    <!-- 用户信息卡片 -->
    <div v-if="userInfo" class="mb-6">
      <a-card size="small" class="bg-red-50 border-red-200">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3">
            <UserDeleteOutlined class="text-2xl text-red-500" />
            <div>
              <div class="font-medium text-gray-800">{{ userInfo.name }}</div>
              <div class="text-sm text-gray-500">ID: {{ userInfo.id }}</div>
              <div class="text-sm text-gray-500">账号: {{ userInfo.account }}</div>
            </div>
          </div>
        </div>
      </a-card>
      <a-alert
        message="警告"
        description="确定要将此用户从组织中移除吗？此操作不可恢复。"
        type="error"
        show-icon
        class="mt-4"
      />
    </div>

    <!-- 操作按钮 -->
    <div class="flex justify-end gap-2">
      <a-button @click="handleReset">重置</a-button>
      <a-button @click="emit('close')">取消</a-button>
      <a-button
        danger
        type="primary"
        :loading="loading"
        :disabled="!userInfo"
        @click="handleRemoveMember"
      >
        移除成员
      </a-button>
    </div>
  </div>
</template>

<style scoped>
.remove-member-dialog {
  padding: 0;
}
</style>
